package com.baibei.ebec.user.address;

import android.content.Context;
import android.text.TextUtils;

import com.baibei.basic.BasicPresenterImpl;
import com.baibei.basic.module.validator.PhoneValidator;
import com.baibei.ebec.sdk.ApiFactory;
import com.baibei.ebec.sdk.IUserApi;
import com.baibei.model.AddressInfo;
import com.baibei.sdk.ApiDefaultObserver;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rae.widget.dialog.model.LocationProvinceInfoBean;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;


/**
 * 收货地址
 * Created by ChenRui on 2016/8/13 0013.
 */
public class AddressEditPresenterImpl extends BasicPresenterImpl<AddressEditContract.View> implements AddressEditContract.Presenter {

    private IUserApi mUserApi;
    private PhoneValidator mPhoneValidator = new PhoneValidator();


    public AddressEditPresenterImpl(Context context, AddressEditContract.View view) {
        super(context, view);
        mUserApi = ApiFactory.getInstance().getUserApi();
    }


    @Override
    public void addAddress() {
        final AddressInfo m = mView.getAddressInfo();
        if (checkAddressIsFailed(m)) return;
        createObservable(mUserApi.addAddress(m.getMobile(), m.getAddress(), m.getReceiver(), m.getZipCode(), m.getRegion(), m.isDefault() ? 1 : 0))
                .subscribe(new ApiDefaultObserver<AddressInfo>() {
                    @Override
                    protected void onError(String s) {
                        mView.onUpdateAddressFailed(0, s);
                    }

                    @Override
                    protected void accept(AddressInfo data) {
                        mView.onAddAddressSuccess(data);
                    }
                });

    }

    @Override
    public void updateAddress() {
        final AddressInfo m = mView.getAddressInfo();
        if (checkAddressIsFailed(m)) return;

        if (TextUtils.isEmpty(m.getId())) {
            mView.onUpdateAddressFailed(4, "获取地址信息错误，请退出重新填写。");
            return;
        }

        createObservable(mUserApi.updateAddress(m.getId(), m.getMobile(), m.getAddress(), m.getReceiver(), m.getZipCode(), m.getRegion(), m.isDefault() ? 1 : 0))
                .subscribe(new ApiDefaultObserver<AddressInfo>() {
                    @Override
                    protected void onError(String s) {
                        mView.onUpdateAddressFailed(0, s);
                    }

                    @Override
                    protected void accept(AddressInfo data) {
                        mView.onUpdateAddressSuccess();
                    }
                });

    }

    /**
     * 校验信息是否通过
     *
     * @return true　不通过
     */
    private boolean checkAddressIsFailed(AddressInfo m) {
        if (TextUtils.isEmpty(m.getReceiver())) {
            mView.onUpdateAddressFailed(1, "请填写收货人");
            return true;
        }
        if (TextUtils.isEmpty(m.getMobile())) {
            mView.onUpdateAddressFailed(2, "请填写手机号码");
            return true;
        }
        if (!mPhoneValidator.isMobile(m.getMobile())) {
            mView.onUpdateAddressFailed(2, "请填写正确的手机号码");
            return true;
        }
        if (TextUtils.isEmpty(m.getAddress()) || TextUtils.isEmpty(m.getRegion())) {
            mView.onUpdateAddressFailed(3, "请填写收货地址");
            return true;
        }
//        if (TextUtils.isEmpty(m.getZipCode())) {
//            mView.onUpdateAddressFailed(3, "请填写邮政编码");
//            return true;
//        }
        return false;
    }


    @Override
    public void start() {
        loadLocationData();
    }


    /**
     * 加载地区数据
     */
    private void loadLocationData() {
        // 加载地区列表
        String json = readAssets("sph_district.json");
        if (json == null) {
            mView.onLoadAreaDataFailed("读取地区数据出错");
            return;
        }

        List<LocationProvinceInfoBean> result = new Gson().fromJson(json, new TypeToken<List<LocationProvinceInfoBean>>() {
        }.getType());

        mView.onLoadAreaDataSuccess(result);
    }

    /**
     * 读取资源
     *
     * @param fileName
     * @return
     */
    protected String readAssets(String fileName) {
        try {
            InputStream stream = mContext.getResources().getAssets().open(fileName);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(stream);
            int len = 0;
            byte[] temp = new byte[512];

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            while ((len = bufferedInputStream.read(temp)) != -1) {
                outputStream.write(temp, 0, len);
            }

            String result = outputStream.toString();

            bufferedInputStream.close();
            stream.close();
            outputStream.close();

            return result;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
